﻿using System.Linq;
using Microsoft.SharePoint.Client;

namespace Sources
{
	/// <summary>
	/// Manage the binding of fields
	/// </summary>
	public static class BindingManager
	{
		/// <summary>
		/// Bind a lookup to its target
		/// </summary>
		/// <param name="context">SharePoint context</param>
		/// <param name="field">Field data to bind to</param>
		/// <param name="returnField">SharePoint field reference</param>
		public static void BindLookup(ClientContext context, FieldArtefact field, Field returnField)
		{
			context.Load(context.Web.Lists, lists => lists.Include(l => l.Title, l => l.Id));
			context.ExecuteQuery();

			var list = context.Web.Lists.FirstOrDefault(lst => lst.Title == field.ListName);

			if (list == null)
			{
				return;
			}
			var fld = returnField.TypedObject as FieldLookup;

			context.Load(fld, f => f.LookupField, f => f.LookupList);
			context.ExecuteQuery();

			fld.LookupList = list.Id.ToString("B");
			fld.LookupField = field.FieldRef;
			fld.Update();
			context.ExecuteQuery();
		}
	}
}
